/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024.
 * Description: supports configurable overrunlog period in cmdline
 * Author: shixin <shixin21@huawei.com>
 * Create: 2024-02-21
 */

#include <linux/init.h>
#include <linux/string.h>
#include <linux/kstrtox.h>
#include <linux/printk.h>

#define TTY_NAME_LENGTH_LIMIT  16
#define SETVAL_SECOND_DEFAULT  1UL
#define SETVAL_SECOND_MAX      (10 * 24 * 60 * 60UL) /* 10 days to second */

static struct _n_tty_overrunlog_config
{
	char name[TTY_NAME_LENGTH_LIMIT];
	unsigned long period; /* unit: Hz */
} n_tty_overrunlog_config = {
	.name = { 0 },
	.period = HZ,
};

static int __init n_tty_overrunlog_setup(char *str)
{
	char buf[TTY_NAME_LENGTH_LIMIT];
	char *s;
	unsigned long setval; /* unit: s */
	unsigned long period; /* unit: Hz */
	int r;

	/* copy to buf */
	strlcpy(buf, str, TTY_NAME_LENGTH_LIMIT);

	/* parse parameter */
	for (s = buf; *s; s++) {
		if (*s == ',') {
			*(s++) = 0;
			break;
		}
	}

	/* set ttyname */
	strlcpy(n_tty_overrunlog_config.name, buf, TTY_NAME_LENGTH_LIMIT);

	/* set overrunlog period */
	r = kstrtoul(s, 0, &setval);
	if (r == 0) {
		if (setval > SETVAL_SECOND_MAX) {
			pr_info("TTY overrun: setval exceeds the max(10 days), using the max\n");
			setval = SETVAL_SECOND_MAX;
		} else if (setval == 0) {
			pr_info("TTY overrun: setval is 0, using default 1s\n");
			setval = SETVAL_SECOND_DEFAULT;
		}
	} else {
		/* maybe parsing error, so use default period */
		pr_info("TTY overrun: unknown format, using default 1s\n");
		setval = SETVAL_SECOND_DEFAULT;
	}

	pr_info("TTY overrun: the set period is %lus\n", setval);

	period = setval * HZ;
	n_tty_overrunlog_config.period = period;

	return 1;
}
__setup("tty_overrunlog_period=", n_tty_overrunlog_setup);

void get_n_tty_overrun_period(char *ttyname, unsigned long *outtime)
{
	if (!strcmp(ttyname, n_tty_overrunlog_config.name))
		*outtime = n_tty_overrunlog_config.period;
}

